import { onMounted, onUnmounted, Ref, ref } from "vue";

const useClickOutside = (elementRef: Ref<null | HTMLElement>) => {

    const isClickOutside = ref(false);
    const handler = (e: MouseEvent) => {
        // console.log(e.target);
        if (elementRef.value && e.target)  {
            // 判断点击是否在它内部
            // EventTarget <- Node <- Element <- HTMLElement
            // target可能是Element,Document,Window
            if (elementRef.value.contains(e.target as HTMLElement)) {
                isClickOutside.value = false;
                
            } else {
                isClickOutside.value = true;
            }
        }
    }

    onMounted(() => {
        document.addEventListener('click', handler);
    })
    onUnmounted(() => {
        document.removeEventListener('click', handler);
    })
    return isClickOutside;

};

export default useClickOutside;
